import json
import os

from redis.client import StrictRedis
from redis.connection import ConnectionPool

from utils.singleton import singleton


@singleton
class RedisUtil:
    def __init__(self):
        current_path = os.path.dirname(os.path.abspath(__file__))
        root_path = os.path.dirname(current_path) + '/resource/config.json'
        with open(root_path, 'r') as f:
            config = json.load(f)
        host = config['redis']['host']
        port = int(config['redis']['port'])
        pwd = config['redis']['password']
        pool = ConnectionPool(host=host, port=port, db=0, password=pwd)
        self.redis = StrictRedis(connection_pool=pool)

    def hsetnx(self, name, key, value):
        self.redis.hsetnx(name, key, value)

    def hgetall(self, name):
        get_result = self.redis.hgetall(name)
        result = {}
        for key, value in get_result.items():
            result[key.decode('utf-8')] = value.decode('utf=8')
        return result

    def delete(self, name):
        self.redis.delete(name)

    def hexists(self, name, key):
        return self.redis.hexists(name, key)

    def hset(self, name, key, value):
        self.redis.hset(name, key, value)


if __name__ == '__main__':
    redis = RedisUtil()
    # redis.hsetnx('user', 'name', '李凯')
    # redis.hsetnx('user', 'age', 18)
    redis.hset('user', 'age', 20)
    redis.hset('user', 'sex', '男')
